﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace BillingManagment
{
    public class DbConnect
    {
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connection"].ToString());

        public DbConnect()
        {
        }

        public DataTable GetDataTable(string command_text, CommandType commandType, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = command_text;
            cmd.CommandType = commandType;
            cmd.Connection = con;
            AttachParameters(cmd, commandParameters);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable ds = new DataTable();
            da.Fill(ds);
            return ds;
        }

        public DataSet GetDataSet(string command_text, CommandType commandType, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = command_text;
            cmd.CommandType = commandType;
            cmd.Connection = con;
            AttachParameters(cmd, commandParameters);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }

        public void ExecuteQuery(string command_text, CommandType commandType, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = command_text;
            cmd.CommandType = commandType;
            cmd.Connection = con;
            AttachParameters(cmd, commandParameters);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable ds = new DataTable();
            da.Fill(ds);
        }

        private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
        {
            if (command == null)
                throw new ArgumentNullException("command");

            if (commandParameters != null)
                foreach (SqlParameter p in commandParameters)
                    if (((p != null)))
                    {
                        if ((p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Input) && p.Value == null)
                            p.Value = DBNull.Value;
                        command.Parameters.Add(p);
                    }
        }
    }
}